/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.jit.core.compile;

import javax.tools.SimpleJavaFileObject;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * @author Kaixuan Shi
 * @since 2023/8/24
 */
public class BytesJavaFileObject extends SimpleJavaFileObject {
    private final String className;
    private ByteArrayOutputStream classBytesOs;

    public BytesJavaFileObject(String className, Kind kind) {
        super(fromClassName(className), kind);
        this.className = className;
    }

    private static URI fromClassName(String className) {
        try {
            return new URI(className);
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException(className, e);
        }
    }

    /**
     * 编译结果回调的OutputStream，回调成功后通过getClassBytes()方法获取目标类编译后的字节码字节数组
     */
    @Override
    public OutputStream openOutputStream() {
        return classBytesOs = new ByteArrayOutputStream();
    }

    public byte[] getClassBytes() {
        return classBytesOs.toByteArray();
    }

    public String getClassName() {
        return className;
    }

}
